package com.ngc.mall.common.configure.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.ngc.mall.common.configure.exception.BusinessException;
import lombok.Data;

import java.io.Serializable;

@Data
public class ResponseResult<T> implements Serializable {
    public static final ResponseResult SUCCESS = new ResponseResult(ResponseCode.SUCCESS);

    private static final long serialVersionUID = -2769676829184404994L;

    @JsonInclude
    private T data;

    private Integer code;

    private  String message;

    private String throwable;

    public ResponseResult(ResponseCode code,T data) {
        super();
        this.code=code.code();
        this.message=code.message();
        this.data=data;
    }

    public ResponseResult(){
        super();
    }

    public ResponseResult(ResponseCode code,String message){
        super();
        this.code=code.code();
        this.message=message;
    }

    public ResponseResult(ResponseCode code){
        super();
        this.code=code.code();
        this.message=code.message();
    }

    /**
     * 异常的响应结果，返回的对象会包含 {@code throwable} 字段
     *
     * @param code      {@link ResponseCode}
     * @param throwable {@link Throwable}
     */
    public ResponseResult(ResponseCode code, Throwable throwable) {
        super();
        this.code = code.code();
        this.message = code.message();
        this.throwable = throwable.getMessage();
    }

    public ResponseResult(Throwable throwable) {
        super();
        this.throwable = throwable.getMessage();
    }

    public static <T> ResponseResult<T> success(T data) {
        return new ResponseResult(ResponseCode.SUCCESS, data);
    }

    public static <T> ResponseResult<T> success() {
        return new ResponseResult(ResponseCode.SUCCESS);
    }
    /**
     * 根据返回值，自动选择返回的结果
     *
     * @param bool
     * @return
     */
    public static ResponseResult<Boolean> auto(boolean bool) {
        if (bool) {
            return ResponseResult.success();
        } else {
            return ResponseResult.failure();
        }
    }

    public static <T> ResponseResult<T> failure() {
        return new ResponseResult(BusinessException.failure("失败"));
    }
}
